import React, { useState, useEffect } from 'react';

import { SearchOutlined } from '@ant-design/icons';

import type {
  DeviceItemDetail,
  SysServicesRecord,
  SysUploadDataOldType,
} from '@/api/deviceManagerApi';
import { deviceManagerServiceRecordApi } from '@/api/deviceManagerApi';
import { ServiceStatusList, getEnumLabel } from '@/constants';

const { RangePicker } = ADatePicker;

interface ServiceRecordsProps {
  deviceDetail: DeviceItemDetail;
  reportData: SysUploadDataOldType | null;
  reportLoading: boolean;
}

/**
 * 服务记录组件
 */
const ServiceRecords: React.FC<ServiceRecordsProps> = ({
  deviceDetail,
  reportData: _reportData,
  reportLoading: _reportLoading,
}) => {
  const [form] = AForm.useForm();
  const [loading, setLoading] = useState(false);
  const [records, setRecords] = useState<SysServicesRecord[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  // 获取服务记录数据
  const fetchServiceRecords = async (page = 1, pageSize = 20) => {
    setLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const params: any = {
        page,
        pageSize,
        deviceCode: deviceDetail.code,
        productCode: deviceDetail.productCode,
      };

      // 确保设备编码存在
      if (!deviceDetail.code) {
        console.warn('设备编码为空，无法查询服务记录');
        setRecords([]);
        setPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
        setLoading(false);
        return;
      }

      // 添加搜索关键词
      if (formValues.searchKey && formValues.searchKey.trim()) {
        params.searchKey = formValues.searchKey.trim();
      }

      // 添加时间范围
      if (formValues.dateRange && formValues.dateRange[0] && formValues.dateRange[1]) {
        params.startTime = formValues.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        params.endTime = formValues.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
      }

      // 调试日志：确认参数
      console.log('服务记录查询参数:', params);

      const res = await deviceManagerServiceRecordApi(params);

      if (res.success && res.data) {
        const records = res.data.records || [];
        const total = res.data.total || 0;

        setRecords(records);
        setPagination({
          current: page,
          pageSize,
          total,
        });
      } else {
        setRecords([]);
        setPagination({
          current: 1,
          pageSize: 20,
          total: 0,
        });
      }
    } catch (error) {
      console.error('获取服务记录失败:', error);
      window.$message.error('获取服务记录失败');
      setRecords([]);
      setPagination({
        current: 1,
        pageSize: 20,
        total: 0,
      });
    } finally {
      setLoading(false);
    }
  };

  // 搜索处理
  const handleSearch = () => {
    form.validateFields().then(() => {
      fetchServiceRecords(1, pagination.pageSize);
    });
  };

  // 分页变化处理
  const handleTableChange = (page: number, pageSize: number) => {
    fetchServiceRecords(page, pageSize);
  };

  // 初始化数据
  useEffect(() => {
    fetchServiceRecords();
  }, []);

  // 表格列定义
  const columns = [
    {
      title: '服务名称',
      dataIndex: 'serviceName',
      key: 'serviceName',
    },
    {
      title: '标识符',
      dataIndex: 'identifier',
      key: 'identifier',
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
    {
      title: '执行时间',
      dataIndex: 'executionTime',
      key: 'executionTime',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: number) => {
        return getEnumLabel(ServiceStatusList, status, '未知');
      },
    },
    {
      title: '服务参数',
      dataIndex: 'inputParam',
      key: 'inputParam',
      ellipsis: true,
    },
    {
      title: '返回值',
      dataIndex: 'outputParam',
      key: 'outputParam',
      ellipsis: true,
    },
  ];

  return (
    <div className="p-4">
      {/* 查询条件 */}
      <div className="mb-4">
        <AForm form={form} layout="inline" onFinish={handleSearch}>
          <ARow gutter={8} align="middle" style={{ width: '100%' }}>
            <ACol span={12}>
              <AForm.Item name="dateRange" label="时间范围" style={{ marginBottom: 0 }}>
                <RangePicker
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                  placeholder={['开始时间', '结束时间']}
                  style={{ width: '100%' }}
                />
              </AForm.Item>
            </ACol>
            <ACol span={8}>
              <AForm.Item name="searchKey" label="服务名称或标识符" style={{ marginBottom: 0 }}>
                <AInput placeholder="请输入服务名称或标识符" onPressEnter={handleSearch} />
              </AForm.Item>
            </ACol>
            <ACol span={2}>
              <AButton
                type="primary"
                icon={<SearchOutlined />}
                onClick={handleSearch}
                loading={loading}
              >
                搜索
              </AButton>
            </ACol>
          </ARow>
        </AForm>
      </div>

      {/* 数据表格 */}
      <ATable
        columns={columns}
        dataSource={records}
        loading={loading}
        pagination={{
          current: pagination.current,
          pageSize: pagination.pageSize,
          total: pagination.total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 条记录，当前显示第 ${range[0]}-${range[1]} 条`,
          onChange: handleTableChange,
          onShowSizeChange: handleTableChange,
        }}
        scroll={{ y: 400 }}
        size="middle"
      />
    </div>
  );
};

export default ServiceRecords;
